<?php
	class BlogsController extends  AppController{
		var $name = 'Blogs';
		var $uses = array('Blog','User');
		var $component = array('Auth','Cookie');
		var $paginate = array(
				'limit'=> 3,
				'order'=>array('Post.post_time'=>'asc'));
		
		function beforeFilter(){
			//App::import('Model','User');
			parent::beforeFilter();
			$this->Auth->allow('index');
		}
		//there are two kinds of pages .One is for the user ,the other is for dorimemer(It mean the visitor who use dorime.me).
		// This one is for dorimemer .
		function index($blogId = null){
			//$this->theme = 'default';
			$this->view = 'Theme';
			$this->theme = 'default';
			//find the blog's informations and it's host  according to its id .
			$this->loadModel('UsersBlog');
			$result= $this->UsersBlog->find('all',array(
					'conditions'=>array('UsersBlog.blogs_id'=>$blogId,'UsersBlog.status'=>'own'),
					'fields'=>array('Blog.id','Blog.title','Blog.description','Blog.pic','Blog.themeName','Blog.followed_count','Blog.posts_count','Blog.drafts_count',
									'User.id','User.pic','User.username'),
					'order'=>'UsersBlog.id asc'
			));
			// if it is not null ,which means that the blog exists.
			if(!empty($result)){
				// set the page title .
				$title = $result[0]['Blog']['title'] ;
				$this->set('title_for_layout', $title);
				// get the blog's informations and the blog's hosts informations.
				$blogInfo = $result[0]['Blog'] ;
				$blogHosts = null ;
				foreach($result as $key3 => $value3 ){
					$blogHosts[$key3]['id'] = $value3['User']['id'] ;
					$blogHosts[$key3]['pic'] = $value3['User']['pic'] ;
					$blogHosts[$key3]['username'] = $value3['User']['username'] ;
				}
				//find the post published by the current blog.
				$this->loadModel('Post');
			 	$posts = $this->Post->find('all',array(
			 		'conditions'=>array('Post.blogs_id'=>$blogId),
			 		'fields'=>array('Post.id','Post.title','Post.excerpt','Post.reblog_posts_id','Post.users_id','Post.blogs_id','Post.response_count'),
			 		'limit'=>25,
			 		'order'=>'Post.id desc'
			 	));
			 	//find the post's tags ,and insert them into the posts variable ,
			 	//and find if the user like the post or reblog the post
			 	$this->loadModel('PostHasTag');
			 	$this->loadModel('Response') ;
			 	$this->loadModel('User');
			 	$this->PostHasTag->unBindModel( array( 'belongsTo' => array('Post') ));
			 	foreach($posts as $key => $value ){
			 		//find the post's tags.
				 	$tags = $this->PostHasTag->find('all',array(
				 		'conditions'=>array('PostHasTag.posts_id'=>$value['Post']['id']),
				 		'fields'=>array('Tag.id' ,'Tag.name')
				 	));
				 	$i = 0 ;
				 	foreach ($tags as $key1 => $value1 ){
				 		$posts[$key]['Post']['tags'][$i]['name'] = $value1['Tag']['name'] ;
				 		$posts[$key]['Post']['tags'][$i]['id']	 = $value1['Tag']['id'] ;
				 		++$i ;
				 	}
			 	}
			 	// find the people who follow current blog.
			 	$this->UsersBlog->unbindModel(array('belongsTo'=>array('Blog','User')));
			 	$tmp = $this->UsersBlog->find('all',array(
			 		'conditions'=>array('UsersBlog.blogs_id'=>$blogInfo['id'],'UsersBlog.status'=>'follow'),
			 		'fields'=>array('UsersBlog.id', 'UsersBlog.users_id','UsersBlog.blogs_id'),
			 		'order'=>'UsersBlog.id desc',
			 		'limit'=>16
			 	));
			 	$userIDs = null;
			 	foreach($tmp as $key1 => $value1){
			 		$userIDs[$key1] = $value1['UsersBlog']['users_id'] ;
			 	}
			 	$usersInfo = $this->User->find('all',array(
			 		'conditions'=>array('User.id'=>$userIDs),
			 		'fields'=>array('User.id','User.pic','User.username')
			 	));
			 	$users = array();
			 	foreach($usersInfo as $key2 => $value2 ){
			 		$users[$key2] = $value2['User'] ;
			 	}
			 	// set the variable 'followStatus' .There are four stituations:
			 	//1.if the current vistor doesn't login ,then the followStatus is true .It means that the vistor can follow the current blog.
			 	//2.if the vistor has logined and he/she is the blog' host,then don't set  followStatus variable.
			 	//3.if the vistor has logined , he/she isn't the blog's host and he/she doesn't follow the current blog,then set the followStatus  true
			 	//4.if the vistro has logined ,he/she isn't the blog's host and he/she has followed the current blog ,then set the followStatue false;
			 	$followStatus = null;
			 	if(!($this->Auth->user()) ){
			 		// if the user doesn't login.
			 		$this->set('followStatus','1');
			 	}else{
			 		// if the user has login.
			 		$cookie = $this->Cookie->read('Auth.User');
			 		$this->UsersBlog->unbindModel(array('belongsTo'=>array('User','Blog')));
			 		$tmpInfo = $this->UsersBlog->find('first',array(
			 			'conditions'=>array('UsersBlog.users_id'=>$cookie['id'],'UsersBlog.blogs_id'=>$blogInfo['id'],'UsersBlog.status'=>'own' ),
			 			'fields'=>array('UsersBlog.id') ));
			 		if(empty($tmpInfo)){
			 			// if the user isn't  the host of the blog.
			 			$tmpInfo2 = $this->UsersBlog->find('first',array(
			 				'conditions'=>array('UsersBlog.users_id'=>$cookie['id'],'UsersBlog.blogs_id'=>$blogInfo['id'],'UsersBlog.status'=>'follow'),
			 				'fields'=>array('UsersBlog.id')	));
			 			if($tmpInfo2){
			 				// if there is record ,it means the vistor has follow the blog. Set the followStatus false ,
			 				$this->set('followStatus','0');
			 			}else{
			 				// the vistor doesn't follow the blog.
			 				$this->set('followStatus','1');
			 			}
			 		}
			 		// if the user is the host of the blog ,don't set the variable
			 	}
			 	// find the current blog's  first host's following blog.
			 	$FollowingPeople = null ;
			 	$FollowingPeopleTmp = $this->UsersBlog->find('all',array(
			 			'conditions'=>array('UsersBlog.users_id'=>$blogHosts[0]['id'],'UsersBlog.status'=>'follow'),
			 			'fields'=>array('User.id','User.username','User.pic','Blog.id'),
			 			'order'=>'UsersBlog.id desc',
			 			'limit'=> 16
			 		)
			 	);
			 	foreach($FollowingPeopleTmp as $key4 => $value4){
			 		$FollowingPeople[$key4] = $value4['User'] ;
			 		$FollowingPeople[$key4]['blogs_id'] = $value4['Blog']['id'] ;
			 	}
			 	$this->set('posts',$posts);// the post of the current blog.
			 	$this->set('blog',$blogInfo);// the blog 's informations.
			 	$this->set('users',$users);// the user follow current blog.
			 	$this->set('blogHosts',$blogHosts);// the host of the blog.
			 	$this->set('followingPeople',$FollowingPeople);// the blogs that the first host of the blog has followed .
			}else{
				$this->redirect('/error') ;
			}
		}
	
	
		/**
		 * 
		 * the method is for adding  a new blog
		 */
		function add(){
			//if the empty is not null ,it indicates that user want to create a new blog,update the blog data.
			if(!empty($this->data) ){
				$this->Blog->id = null ;
					$blogInfo = array(
						'Blog'=>array( 'title'=>$this->data['Blog']['Title'],
							'password'=>$this->data['Blog']['password'],
							'url'=>$this->data['Blog']['url'] ));
					if($this->Blog->save($blogInfo)){
						$id = $this->Auth->user('id');
						$this->loadModel('UsersBlog');
						$this->UsersBlog->id = null ;
						$this->UsersBlog->save(array(
							'UsersBlog'=>array(
								'users_id'=>$id,
								'blogs_id'=>$this->Blog->id,
								'status'=>'own'
							)
						));
						$this->redirect(array('controller'=>'dashboard','action'=>'index') ) ;
					}
			}else{
					$email = $this->Auth->user('email');
					// if the $this->data is null ,it indicates that someone redirect to this page.
					if( !empty($email) ){
						$result = $this->User->findByEmail($email);
						// if the email is not null ,we check if tshee is  such a email in the datebasse. 
						if(!empty($result)){
							$urlAnID = array(
								'url'=>$result['User']['username'],
							);
							$this->set('blogInfo',$urlAnID);
						}else{
							$this->redirect(array('controller'=>'Users','action'=>'login'));
						}
					}
				}
		}
		function customize(){
			$this->layout = 'customize';
			$this->set('theme','default');
		}
		function template($theme = null){
			$this->layout = null;
			$this->set('theme',$theme);
		}
		/**
		 * 
		 * This function is for updating a new blog after a user has regitered .
		 * @param unknown_type $blogID
		 */
		function update($blogID = null ){
			if(empty($this->data)){
				$email = $this->Auth->user('email') ;
				$this->loadModel('UsersBlog') ;
				$blog = $this->UsersBlog->find('first',array(
					'conditions'=>array('User.email'=>$email,'Blog.id'=>$blogID),
					'fields'=>array('User.id','Blog.id','Blog.title','Blog.description','Blog.url','Blog.password','Blog.themeName')
				));
				if(!empty($blog) ) {
					$blog = $blog['Blog'] ;
					$this->set('blogInfo',$blog);
				}else{
					// if the blog doesn't belong to the user ,redirect to the 'dashboard'
					$this->redirect(array('controller'=>'dashboard','action'=>'index'));
					exit ;
				}
			}else{
				//Get the user .
				$blogID = $this->data['Blog']['id'] ;
				$email = $this->Auth->user('email') ;
				$this->loadModel('UsersBlog')  ;
				// find whether the blog has exist.
				$blog = $this->UsersBlog->find('first',array(
					'conditions'=>array('User.email'=>$email,'Blog.id'=>$blogID),
					'fields'=>array('User.id','Blog.id')
				));
				// if the blog has exsited.
				if(!empty($blog)){
					$this->Blog->id = $blogID ;
					$blogInfo = array(
						'Blog'=>array(
							'title'=>$this->data['Blog']['Title'],
							'url'=>$this->data['Blog']['url'],
							'password'=>$this->data['Blog']['password'],
						)
					);
					// update the blog.
					if( $this->Blog->save($blogInfo) ){
						$this->redirect(array('controller'=>'explore'));
						exit ;
					}else{
						// if update failed .Go back to the page 'blogs/update'.
						$info = $this->Blog->find('first',array(
							'conditions'=>array('Blog.id'=>$blogID),
								'fields'=>array('Blog.id','Blog.url')
						));
						$this->set('blogInfo',$info['Blog']);
						exit ;
					}
				}
				$this->redirect(array('controller'=>'dashboard','action'=>'index'));
				exit ;
			}
		}
	}
?>